export default {
  methods: {
    async $sendMessageCommon(messageData) {
      if (!messageData) return;
      try {
        // 预处理（文件上传等）由调用方负责，以便保持灵活
        // 生成 tempId 并设置自己消息标记
        const message = { ...messageData };
        if (!message.tempId) {
          message.tempId = `temp_${Date.now()}_${Math.random()}`;
        }
        message.isMyselfMsg = true;

        // 乐观添加
        this.$store.dispatch("chat/addOptimisticMessage", {
          chatId: this.$store.getters["chat/currentChatId"],
          message,
        });

        // 发送到服务器
        const res = await this.$service?.({
          method: "POST",
          url: "friend_chat/send",
          data: message,
        }) || await (await import("@/utils/request"))?.default({
          method: "POST",
          url: "friend_chat/send",
          data: message,
        });

        if (res && res.code === 200) {
          this.$store.dispatch("chat/updateMessageStatus", {
            tempId: message.tempId,
            status: "success",
            realMessage: res.data,
          });
          this.$store.dispatch("chatList/updateLatestMessage", {
            chatId: this.$store.getters["chat/currentChatId"],
            message: message.content,
            messageType: message.messageType || "text",
          });
        } else {
          this.$store.dispatch("chat/updateMessageStatus", {
            tempId: message.tempId,
            status: "failed",
            error: (res && res.message) || "发送失败",
          });
        }

        return message;
      } catch (error) {
        this.$store.dispatch("chat/updateMessageStatus", {
          tempId: messageData.tempId,
          status: "failed",
          error: error.message || "网络错误",
        });
        throw error;
      }
    },
  },
};
